package commons.util;

import destinychild.Raid;
import fgoScript.exception.AppNeedRestartException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.*;

/**
 * @author RENZHEHAO
 * @version 1.0.0
 * @ClassName ThreadUtil.java
 * @Description 线程工具类
 * @createTime 2019年11月06日 17:11:00
 */
public class ThreadUtil {
    private static final Logger LOGGER = LogManager.getLogger(ThreadUtil.class);
    /**
     * @Description: 当线程池无活动时，执行下一步
     * @return: void
     * @throw:
     * @Author: RENZHEHAO
     * @Date: 2019/6/7
     */
    public static void waitUntilNoneThread(ThreadPoolTaskExecutor threadPoolTaskExecutor) throws AppNeedRestartException {
        int count = 0;
        do{
            GameUtil.delay(3000);
            if(count++ > 100){
                throw new AppNeedRestartException();
            }
        } while (threadPoolTaskExecutor.getActiveCount() != 0);
    }
    public static void waitUntilNoneThreadWithOutCount(ThreadPoolTaskExecutor threadPoolTaskExecutor) {
        LOGGER.info("线程池：" + threadPoolTaskExecutor.getThreadNamePrefix() + "开始等待线程。。。");
        int count = 0;
        int tempCount = 0;
        do{
            count = threadPoolTaskExecutor.getActiveCount();
            if (tempCount != count){
                tempCount = count;
                LOGGER.info("线程池个数为： " + count + " 个");
            }
            GameUtil.delay(3000);
        } while (threadPoolTaskExecutor.getActiveCount() != 0);
        LOGGER.info("线程池：" + threadPoolTaskExecutor.getThreadNamePrefix() + "线程个数为0了");
    }
    public static void waitUntilFutureFinished(Future ft) {
        LOGGER.info("开始等待Future！");
        boolean finished;
        do{
            finished = ft.isDone();
            GameUtil.delay(3000);
        } while (!finished);
        LOGGER.info("Future对象执行完成！");
    }
    public static void waitUntiloneThread(ThreadPoolTaskExecutor te) throws AppNeedRestartException {
        int count = 0;
        do{
            GameUtil.delay(3000);
            if(count++ > 100){
                throw new AppNeedRestartException();
            }
        } while (te.getActiveCount() != 1);
    }
}
